package com.dave.gd.facade.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;

import com.dave.gd.common.util.crypt.RC2Cryption;
import com.dave.gd.config.OnleduConstant;
import com.dave.gd.core.base.action.AbstractBaseAction;
import com.dave.gd.core.shiro.CaptchaUsernamePasswordToken;
import com.dave.gd.core.shiro.IncorrectCaptchaException;
import com.dave.gd.core.shiro.ShiroUser;
import com.dave.gd.core.vm.Json;
import com.dave.gd.facade.viewModel.MenuModel;
import com.dave.gd.service.IPermissionService;
import com.dave.gd.sysmgr.domain.entity.Permission;

public class LoginAction extends AbstractBaseAction {
    private static final Logger logger = Logger.getLogger(LoginAction.class);
    private static final long serialVersionUID = -6019556530071263499L;
    private String userName;
    private String password;
    private String captcha;
    private String userMacAddr;
    private String userKey;
    
    @Resource
    private IPermissionService permitService;
    
    
    
    @Action(value = "loadAction")
    public void load() throws Exception {
        Subject subject = SecurityUtils.getSubject();
        CaptchaUsernamePasswordToken token = new CaptchaUsernamePasswordToken();
        token.setUsername(userName);
        token.setPassword(RC2Cryption.encrypt(password).toCharArray());
        token.setCaptcha(captcha);
        token.setRememberMe(true);
        Json json = new Json();
        json.setTitle("登录提示");
        try {
            subject.login(token);
            System.out.println("sessionTimeout===>" + subject.getSession().getTimeout());
            json.setStatus(true);
        } catch (UnknownSessionException use) {
            subject = new Subject.Builder().buildSubject();
            subject.login(token);
            logger.error(OnleduConstant.UNKNOWN_SESSION_EXCEPTION);
            json.setMessage(OnleduConstant.UNKNOWN_SESSION_EXCEPTION);
        } catch (UnknownAccountException ex) {
            logger.error(OnleduConstant.UNKNOWN_ACCOUNT_EXCEPTION);
            json.setMessage(OnleduConstant.UNKNOWN_ACCOUNT_EXCEPTION);
        } catch (IncorrectCredentialsException ice) {
            json.setMessage(OnleduConstant.INCORRECT_CREDENTIALS_EXCEPTION);
        } catch (LockedAccountException lae) {
            json.setMessage(OnleduConstant.LOCKED_ACCOUNT_EXCEPTION);
        } catch (IncorrectCaptchaException e) {
            json.setMessage(OnleduConstant.INCORRECT_CAPTCHA_EXCEPTION);
        } catch (AuthenticationException ae) {
            json.setMessage(OnleduConstant.AUTHENTICATION_EXCEPTION);
        } catch (Exception e) {
            json.setMessage(OnleduConstant.UNKNOWN_EXCEPTION);
        }
        writeJson(json);
        // token.clear();
    }
    
    /**
     * 函数功能说明 TODO:用户登出 Administrator修改者名字 2013-5-9修改日期 修改内容
     * 
     * @Title: logout
     * @Description:
     * @param @return
     * @param @throws Exception 设定文件
     * @return String 返回类型
     * @throws
     */
    @Action(value = "logout")
    public void logout() throws Exception {
        SecurityUtils.getSubject().logout();
        Json json = new Json();
        json.setStatus(true);
        writeJson(json);
    }
    
    /**
     * 函数功能说明 TODO:查询用户所有权限菜单 Administrator修改者名字 2013-5-9修改日期 修改内容
     * 
     * @Title: findAllFunctionList
     * @Description:
     * @param @return
     * @param @throws Exception 设定文件
     * @return String 返回类型
     * @throws
     */
    @Action(value = "findAllFunctionList")
    public void findAllFunctionList() throws Exception {
        // OutputJson(loginService.findMenuList());
        // writeJson();
        Subject subject = SecurityUtils.getSubject();
        ShiroUser shiroUser = (ShiroUser) subject.getSession().getAttribute(OnleduConstant.SHIRO_USER);
        if (shiroUser != null) {
            List<Permission> permissions = permitService.findPermissionListByUserId(shiroUser
                .getUserId());
            List<MenuModel> parentMenuList = new ArrayList<MenuModel>();
            for (Permission p : permissions) {
                if (p.getPid() == -1 ||p.getPid() == 0 || p.getPid() == null || "".equals(p.getPid())) {//-1或"",都可能是根节点
                    MenuModel menuModel = new MenuModel();
                    menuModel.setName(p.getName());
                    menuModel.setIconCls(p.getIcons());
                    menuModel.setUrl(p.getUrl());
                    
                    List<MenuModel> childMenuList = new ArrayList<MenuModel>();
                    for (Permission childP : permissions) {
                        if (childP.getPid() != null|| !"".equals(childP.getPid())) {//-1或"",都可能是根节点
                            if (p.getId() == childP.getPid()) {
                                MenuModel childMenuModel = new MenuModel();
                                childMenuModel.setName(childP.getName());
                                childMenuModel.setIconCls(childP.getIcons());
                                childMenuModel.setUrl(childP.getUrl());
                                childMenuList.add(childMenuModel);
                            }
                        }
                    }
                    menuModel.setChild(childMenuList);
                    parentMenuList.add(menuModel);
                }
            }
            writeJson(parentMenuList);
        }
    }
    
    
    public String getUserKey() {
        return userKey;
    }
    
    public void setUserKey(String userKey) {
        this.userKey = userKey;
    }
    
    public String getUserMacAddr() {
        return userMacAddr;
    }
    
    public void setUserMacAddr(String userMacAddr) {
        this.userMacAddr = userMacAddr;
    }
    
    public String getCaptcha() {
        return captcha;
    }
    
    public void setCaptcha(String captcha) {
        this.captcha = captcha;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
}
